The instanceof
construction is a preferred way to check whether a variable can be cast to some type statically because a compile-time
error will occur in case of incompatible types. The method isInstance() from java.lang.Class
works differently and does type check at runtime only, incompatible types will therefore not be detected early in the development, potentially
resulting in dead code. The isInstance()
method should only be used in dynamic cases when the instanceof
operator can’t be
used.
This rule raises an issue when isInstance()
is used and could be replaced with an instanceof
check.
Noncompliant code example
int f(Object o) {
if (String.class.isInstance(o)) { // Noncompliant
return 42;
}
return 0;
}
int f(Number n) {
if (String.class.isInstance(n)) { // Noncompliant
return 42;
}
return 0;
}
Compliant solution
int f(Object o) {
if (o instanceof String) { // Compliant
return 42;
}
return 0;
}
int f(Number n) {
if (n instanceof String) { // Compile-time error
return 42;
}
return 0;
}
boolean fun(Object o, String c) throws ClassNotFoundException
{
return Class.forName(c).isInstance(o); // Compliant, can't use instanceof operator here
}